<?php

namespace App\Http\Controllers\User;

use App\Http\Classes\Teacher;
use App\Http\Classes\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    //
    public function login(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['username']) && isset($data['password']) && isset($data['rule']))
            {
                $token = new User();
                $token = $token->login($data);
                if ($token === null)
                {
                    return $this->response(0,'',$token);
                }
                else if($token === false)
                {
                    return $this->response(0,'用户名，密码和角色不匹配',$token);
                }
                else
                {
                    $res = [];
                    $res['token'] = $token['token'];
                    $res['userId'] = $token['userId'];
                    $res['teacherId'] = null;
                    setcookie('TOKEN', $token['token'], time()+3600*24*7, '/');
                    if ( $data['rule'] == 1 )
                    {
                        $teacher = new Teacher();
                        $teacher = $teacher->getTeacherIdByUserId($token['userId']);
                        $res['teacherId'] = $teacher;
                    }
                    return $this->response(1, 'success', $res);
                }
            }
            else
            {
                return $this->response(0, '缺少参数', null);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception);
        }
    }

    public function updatePassword(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['oldpassword']) && isset($data['newpassword1']) )
            {
                $user = new User($data['userid']);
                $user = $user->updatePassword($data['oldpassword'], $data['newpassword1']);
                if ($user === null)
                {
                    return $this->response(0, '旧密码不匹配', null);
                }
                else if($user === false)
                {
                    return $this->response(0, '未知错误，更新失败', null);
                }
                else
                {
                    return $this->response(1, '更新密码成功！', null);
                }
            }
            else
            {
                return $this->response(0, '缺少参数', null);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception);
        }
    }
}
